﻿using System;
using System.Web.Mvc;
using StudentInfo.Areas.AccountArea.Models;
using System.Web.Routing;
using StudentInfo.Areas.AccountArea.Services;
using StudentInfo.Areas.AccountArea.Helpers;
using StudentInfo.EmailServices;
using System.Web.UI;
using StudentInfo.Security.Services;
using System.Globalization;

namespace StudentInfo.Areas.AccountArea.Controllers
{
    public class AccountController : Controller
    {
        public IFormsAuthenticationService FormsService { get; set; }

        protected override void Initialize(RequestContext requestContext)
        {
            if (FormsService == null) { FormsService = new FormsAuthenticationService(); }

            base.Initialize(requestContext);
        }

        // **************************************
        // URL: /Account/LogOn
        // **************************************

        public ActionResult LogOn()
        {
            return View();
        }

        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                var account = AccountService.Get(model.AccountName, model.Password);

                if (account != null)
                {
                    FormsService.SignIn(model.AccountName, model.RememberMe);

                    if (Url.IsLocalUrl(returnUrl))
                    {
                        return Redirect(returnUrl);
                    }

                    return RedirectToAction("Index", "Home", new { area = "" });
                }
                else
                {
                    ModelState.AddModelError("", "User has not found");
                }
            }
                
            // If we got this far, something failed, redisplay form
            return View(model);
        }

        // **************************************
        // URL: /Account/LogOff
        // **************************************

        public ActionResult LogOff()
        {
            FormsService.SignOut();

            return RedirectToAction("Index", "Home", new { area = "" });
        }

        // **************************************
        // URL: /Account/Register
        // **************************************

        public ActionResult Register()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                var account = AccountHelper.PopulateAccountFromRegisterViewModel(model);
                AccountService.Create(account);

                EmailService.SendVerifyNewUserMessage(account, model.Password,
                    Request.Url.GetLeftPart(UriPartial.Authority) + Request.ApplicationPath,
                    "AccountArea/Account/VerifyNewAccount",
                    Request.PhysicalApplicationPath);

                return RedirectToAction("ConfirmRegistration", "Account");
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        [OutputCache(Location = OutputCacheLocation.None, NoStore = true)]
        public JsonResult IsAccountAvailable(string accountName)
        {
            return Json(!AccountService.IsExistedByName(accountName), JsonRequestBehavior.AllowGet);
        }

        public ActionResult ConfirmRegistration()
        {
            return View();
        }
        
        public ActionResult VerifyNewAccount(Guid id)
        {
            var account = AccountService.GetById(id);

            if (account != null && !account.IsApproved)
            {
                account.IsApproved = true;
                AccountService.Save(account);
                User user = new User { Id = id, UserName = account.AccountName };
                UserService.Create(user);

                FormsService.SignIn(account.AccountName, true);

                return RedirectToAction("Index", "Home", new { area = "" });
            }

            return View();
        }

        #region changepassword
        // **************************************
        // URL: /Account/ChangePassword
        // **************************************

        //[Authorize]
        //public ActionResult ChangePassword()
        //{
        //    ViewBag.PasswordLength = MembershipService.MinPasswordLength;
        //    return View();
        //}

        //[Authorize]
        //[HttpPost]
        //public ActionResult ChangePassword(ChangePasswordModel model)
        //{
        //    if (ModelState.IsValid)
        //    {
        //        if (MembershipService.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword))
        //        {
        //            return RedirectToAction("ChangePasswordSuccess");
        //        }
        //        else
        //        {
        //            ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
        //        }
        //    }

        //    // If we got this far, something failed, redisplay form
        //    ViewBag.PasswordLength = MembershipService.MinPasswordLength;
        //    return View(model);
        //}

        // **************************************
        // URL: /Account/ChangePasswordSuccess
        // **************************************

        //public ActionResult ChangePasswordSuccess()
        //{
        //    return View();
        //}
        #endregion
    }
}
